from api import models
from api.logger import  logger
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import Response
from api.serializers import rbac_serializers
from api.utils.perms import IsOwnerOrReadOnley



#fa0410e516206b1ad9c2efa6c9d3c60e

class RolesViewSet(ModelViewSet):
    # 指定查询集
    queryset = models.Roles.objects.all()
    # 指定序列化器
    serializer_class = rbac_serializers.RoleSerializer


class UsersViewSet(ModelViewSet):
    # 指定查询集
    queryset = models.Users.objects.all()
    # 指定序列化器
    serializer_class = rbac_serializers.UserSerializer
    permission_classes = [IsOwnerOrReadOnley,]


    def get_queryset(self):
        # 如果登陆的是超级用户则返回所有用户，否则只返回自己的信息
        if self.request.user.is_super:
            return models.Users.objects.all()
        else:
            return models.Users.objects.filter(username=self.request.user.username)


    def perform_create(self, serializer):
        serializer.save()
        req_data = self.request.data
        roles = req_data['roles']
        # 添加多对多对象
        obj = models.Users.objects.get(id=serializer.data['id'])
        for i in roles:
            role_obj = models.Roles.objects.get(id=i)
            obj.roles.add(role_obj)
            #把角色信息加入到序列化数据中
            serializer.data['roles'].append({'id':role_obj.id,'title':role_obj.title,'label':role_obj.label})
        return  serializer.data

    def perform_update(self, serializer):
        req_data = self.request.data
        roles = req_data['roles']
        user_id = req_data['id']
        obj = models.Users.objects.get(id=user_id)
        # 清空多对多对象
        obj.roles.clear()
        #添加多对多对象
        for i in roles:
            role_obj = models.Roles.objects.get(id=i['id'])
            obj.roles.add(role_obj)
        serializer.save()

    def perform_destroy(self, instance):
        #清空多对多对象
        instance.roles.clear()
        instance.delete()



